import { Body, Controller, Delete, Param, Post, Put } from '@nestjs/common';
import { BaseController } from 'apps/admin/src/base/base.controller';
import { DbService } from 'apps/admin/src/db/db.service';
import { DtoPipe } from 'apps/admin/src/pipes/dto/dto.pipe';
import { AddDto, UpdateDto } from './dto';
import { DictionaryItem } from '@app/db/common/entities/DictionaryItem';

@Controller('dictionary/item')
export class ItemController extends BaseController{

    constructor(
        private readonly db:DbService
    ){
        super()
    }
    @Post('add')
    async addItem(@Body(new DtoPipe()) dto:AddDto) {
        if((await this.db.dictionaryItem.isExistsByWhere({parentId : dto.parentId || 0, categoryId : dto.categoryId, name : dto.name}))) return this.failRes("已存在相同的名称")
        if((await this.db.dictionaryItem.isExistsByWhere({parentId : dto.parentId || 0, categoryId : dto.categoryId, code : dto.code}))) return this.failRes("已存在相同的编码")
        const res = await this.db.dictionaryItem.insert(dto)
        return res === null ? this.failRes() : this.successRes(res.rows)
    }

    @Put('update/:id')
    async edit(@Param('id') id:number, @Body(new DtoPipe({skipMissingProperties : true})) dto:UpdateDto) {
        const item = await this.db.dictionaryItem.findOne({id : id})
        if(!item) return this.failRes()
        let updateData:{[key in keyof DictionaryItem]? : DictionaryItem[key]} = {}
        if(item.name != dto.name) {
            updateData.name = dto.name
        }
        if(item.code != dto.code) {
            updateData.code = dto.code
        }

        if((Object.keys(updateData)).length == 0) return this.successRes()


        if(updateData.name && (await this.db.dictionaryItem.isExistsByWhere({parentId : item.parentId, categoryId : item.categoryId, name : dto.name}))) return this.failRes("已存在相同的名称")
        if(updateData.code && (await this.db.dictionaryItem.isExistsByWhere({parentId : item.parentId, categoryId : item.categoryId, code : dto.code}))) return this.failRes("已存在相同的编码")
        

        const res = await this.db.dictionaryItem.update({id : id}, updateData)
        return res === 0 ? this.failRes() : this.successRes()
    }

    @Delete('delete/:id')
    async deleteItem(@Param('id') id:number) {
        if((await this.db.dictionaryItem.isExistsByWhere({parentId : id}))) return this.failRes("该分类存在子分类，不可删除")
        const res = await this.db.dictionaryItem.delete({id : id})
        return res === 0 ? this.failRes() : this.successRes()
    }
}
